import base from '../api/base'
import api from '../api/index'
import {
  checkPhone,
  catchError,
  toast,
  _reLogin
} from '../utils/util'
const app = getApp()
// 登录
export const login = () => {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        const code = res.code
        api.login.getToken({
            code
          })
          .then((res) => {
            wx.showToast({
              title: '登录中',
              icon: 'loading',
              duration: 3000
            })
            // _getTokenSucc(res)
            wx.setStorageSync('userInfo', res.data.data)
            resolve(res)
          }).catch((e) => {
            reject(e)
          })
      }
    })
  })
}
// 获取token
export const _getTokenSucc = (res) => {
  const sessionKey = res.header["Set-Cookie"].split(';')[0]
  wx.setStorageSync('sessionKey', sessionKey)
  const data = res.data.data
  if (parseInt(data.state) === 2) {
    wx.showModal({
      title: '温馨提示',
      content: '您已经被禁止使用我们的服务',
      showCancel: false,
      confirmText: '确定',
      success() {
        //非初始化进入该页面,且未授权
        return
      }
    })
  } else {
    return Promise.resolve(res)
  }
}
// 授权
export const authorize = () => {
  wx.getSetting({
    success(res) {
      if (res.authSetting['scope.userInfo']) {
        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
        getUserInfo()
        wx.reLaunch({
          url: '/pages/login/bind/index',
        })
      } else {
        wx.reLaunch({
          url: '/pages/login/index',
        })
      }
    },
    fail() {
      // 重新鉴权
      wx.reLaunch({
        url: '/pages/login/index',
      })
    }
  })
}

// 获取用户信息
export const getUserInfo = () => {
  wx.getUserInfo({
    success(res) {
      res = res.userInfo
      const userInfo = wx.getStorageSync('userInfo')
      const newUserInfo = Object.assign({}, userInfo, {
        nickname: res.nickName,
        headurl: res.avatarUrl
      })
      wx.setStorageSync('userInfo', newUserInfo)
    }
  })
}
// 初始获取用户信息
export const getUserInfoSucc = (res) => {
  res = res.data
  const data = res.data
  const router = wx.getStorageSync('router')
  const flag = checkPhone(data.phone)
  const userInfo = {
    ...data
  }
  if (flag) {
    wx.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 3000,
      success() {
        if (router) {
          return
        }
        wx.reLaunch({
          url: `/pages/index/index`,
        })
      }
    })
    return Promise.resolve(res)
    // setTimeout(() => {
    //   getLocation()
    // }, 1000)
  } else {
    authorize()
    return Promise.reject()
  }
  wx.setStorageSync('userInfo', userInfo)
}

// 获取定位信息
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        const location = wx.getStorageSync('location') || {};
        location.lat = res.latitude;
        location.lng = res.longitude;
        wx.setStorageSync('location', location)
        wx.setStorageSync('changeLocation', location)
        resolve()
      },
      fail: (err) => {
        wx.showModal({
          title: '温馨提示',
          content: '为了给您提供更好的服务,请您授权使用我的地理位置',
          showCancel: false,
          confirmText: '授权',
          success() {
            //非初始化进入该页面,且未授权
            wx.openSetting({
              success(res) {
                const location = wx.getStorageSync('location')
                if (location) {
                  return
                } else {
                  getLocation().then((res) => {
                    resolve()
                  }).catch((res) => {
                    reject()
                  })
                }
              }
            })
          }
        })
        // reject()
      }
    })
  })
}